﻿@page "/admin-settings"
@attribute [Authorize(Roles = "admin")]
@inject IAccessTokenProvider TokenProvider
@inject NavigationManager Navigation

@if(_error == null)
{
    <button id="admin-action" @onclick="AdminAction">Perform admin action</button>
}
else if(_error == true)
{
    <p>Could not get the access token.</p>
}
else if (_error == false)
{
    <p id="admin-success">Successfully perfomed admin action.</p>
}

@code {

    private bool? _error;

    public async Task AdminAction()
    {
        var tokenResult = await TokenProvider.RequestAccessToken();

        if (tokenResult.TryGetToken(out var token))
        {
            var client = new HttpClient() { BaseAddress = new Uri(Navigation.BaseUri) };
            var request = new HttpRequestMessage(HttpMethod.Post, "Roles/AdminOnly");
            request.Headers.Add("Authorization", $"Bearer {token.Value}");
            var response = await client.SendAsync(request);
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                _error = true;
            }
            else
            {
                _error = false;
            }
        }
        else
        {
            _error = true;
        }
    }
}
